package com.meta.platform.file.service.impl;

import com.aliyun.oss.OSSClient;
import com.meta.framework.common.utils.uuid.IdUtils;
import com.meta.platform.file.model.FileInfo;
import com.meta.platform.file.model.FileType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;

/**
 * 阿里云oss存储文件
 **/
@Service("aliyunOssServiceImpl")
public class AliyunOssServiceImplI extends AbstractIFileService {
    @Autowired
    private OSSClient ossClient;
    @Value("${aliyun.oss.bucketName:}")
    private String bucketName;
    @Value("${aliyun.oss.domain:}")
    private String domain;

/*    private String bucketName = "outer-crm-test";
    private String domain = "http://outer-crm-test.oss-cn-shanghai.aliyuncs.com";*/


    @Override
    protected FileType fileType() {
        return FileType.ALIYUN;
    }

    @Override
    protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
        // 构造上传文件唯一路径
        String fileDir =  "crm";
        StringBuilder fileUrl = new StringBuilder();
        String OriginalFilename = file.getOriginalFilename();
        boolean isBlob = ("blob".equals(OriginalFilename));
        String suffix = isBlob ? "" : OriginalFilename.substring(OriginalFilename.lastIndexOf('.'));
        String fileName = isBlob ? IdUtils.randomUUID() : IdUtils.randomUUID() + suffix;
        if(isBlob){
            fileInfo.setName(fileName);
        }

        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);
        ossClient.putObject(bucketName, fileUrl.toString(), file.getInputStream());
        fileInfo.setUrl(domain + "/" + fileUrl.toString());
    }

    @Override
    protected void uploadFile(byte[] file, FileInfo fileInfo) {
        // 构造上传文件唯一路径
        String fileDir =  "crm";
        StringBuilder fileUrl = new StringBuilder();
        String OriginalFilename = fileInfo.getName();
        boolean isBlob = ("blob".equals(OriginalFilename));
        String suffix = isBlob ? "" : OriginalFilename.substring(OriginalFilename.lastIndexOf('.'));
        String fileName = isBlob ? IdUtils.randomUUID() : IdUtils.randomUUID() + suffix;
        if(isBlob){
            fileInfo.setName(fileName);
        }

        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);
        ossClient.putObject(bucketName, fileUrl.toString(), new ByteArrayInputStream(file));
        fileInfo.setUrl(domain + "/" + fileUrl.toString());
    }

//    @Override
//    protected boolean deleteFile(FileInfo fileInfo) {
//        ossClient.deleteObject(bucketName, fileInfo.getName());
//        return true;
//    }
}
